package yun.web.activerecord.dialect.pg;

import yun.web.activerecord.generator.ModelGenerator;
import yun.web.activerecord.generator.TableMeta;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class PGModelGenerator extends ModelGenerator {
    public PGModelGenerator(String modelPackageName, String baseModelPackageName, String modelOutputDir) {
        super(modelPackageName, baseModelPackageName, modelOutputDir);
    }

    @Override
    protected void writeToFile(TableMeta tableMeta) {
        PGTableMeta pgTableMeta = (PGTableMeta) tableMeta;
        File dir = new File(modelOutputDir + File.separator + pgTableMeta.schema_name);
        if (!dir.exists()) {
            dir.mkdirs();
        }


        File file = new File(dir, pgTableMeta.modelName + ".java");
        if (file.exists()) {
            return;   // 若 Model 存在，不覆盖
        }

        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(new FileOutputStream(file), Charset.defaultCharset());
            osw.write(pgTableMeta.modelContent);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
